package com.ship.dispatch.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.bpm.BpmJsonModelDO;
import com.ship.dispatch.bpm.service.BpmModelService;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.vo.*;
import com.ship.dispatch.bpm.vo.dto.TaskDto;
import com.ship.dispatch.bpm.vo.task.BpmTaskApproveReqVO;
import com.ship.dispatch.bpm.vo.task.BpmTaskReqVo;
import com.ship.dispatch.bpm.vo.task.BpmTaskTodoItemRespVO;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.bpm.BpmJsonModelService;
import com.ship.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.catalina.manager.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 模型定义接口类
 */

@Tag(name =  "管理后台 - 流程模型")
@RestController
@RequestMapping("/model")
@Validated
public class BpmModelController {

    @Resource
    private BpmModelService modelService;

    @Resource
    private TaskService taskService;

    @Resource
    ProcessInstanceService processInstanceService;

    @Resource
    BpmJsonModelService bpmJsonModelService;

    @GetMapping("/get")
    @Operation(summary = "获得模型")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public JsonResult<BpmModelRespVO> getModel(@RequestParam("id") String id) {
        BpmModelRespVO model = modelService.getModel(id);
        return JsonResult.success(model);
    }

    @GetMapping("/getByKey")
    @Operation(summary = "获得模型")
    @Parameter(name = "key", description = "编号", required = true, example = "assetget")
    public JsonResult<BpmModelRespVO> getModelByKey(@RequestParam("key") String key) {
        BpmModelRespVO model = modelService.getModel2(key);
        return JsonResult.success(model);
    }

    @PostMapping("/create")
    @Operation(summary = "新建模型")
    public JsonResult<String> createModel(@Valid @RequestBody BpmModelCreateReqVO createRetVO) {
        return JsonResult.success(modelService.createModel(createRetVO, null));
    }

    @PutMapping("/update")
    @Operation(summary = "修改模型")
    public JsonResult<Boolean> updateModel(@Valid @RequestBody BpmModelUpdateReqVO modelVO) {
        modelService.updateModel(modelVO);
        return JsonResult.success();
    }



    @PostMapping("/deploy")
    @Operation(summary = "部署模型")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public JsonResult<Boolean> deployModel(@RequestParam("id") String id) {
        modelService.deployModel(id);
        return JsonResult.success(true);
    }

    @PutMapping("/update-state")
    @Operation(summary = "修改模型的状态", description = "实际更新的部署的流程定义的状态")
    public JsonResult<Boolean> updateModelState(@Valid @RequestBody BpmModelUpdateStateReqVO reqVO) {
        modelService.updateModelState(reqVO.getId(), reqVO.getState());
        return JsonResult.success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除模型")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public JsonResult<Boolean> deleteModel(@RequestParam("id") String id) {
        modelService.deleteModel(id);
        return JsonResult.success(true);
    }

    @PostMapping("/task/page")
    @Operation(summary = "待办任务列表")
    public JsonResult<Page<BpmTaskTodoItemRespVO>> toDoPageList(@RequestBody BpmQueryVo taskReqVo){
        return taskService.todoPageList(taskReqVo);
    }

    @GetMapping("/getProcessAllTaskInfo/{processId}")
    @Operation(summary = "获取指定流程实例任务信息")
    public JsonResult getProcessAllTaskINfo(@PathVariable("processId") String processId){
        return taskService.getProcessAllTaskINfo(processId);
    }

    @GetMapping("/getProcessTaskInfo/{taskId}")
    @Operation(summary = "获取流程任务信息")
    public JsonResult getProcessTaskINfo(@PathVariable("taskId") String taskId){
        return taskService.getProcessTaskINfo(taskId);
    }

    @PostMapping("/page")
    @Operation(summary = "模型列表")
    public JsonResult<Page<BpmJsonModelDO>> getModelPage(@RequestBody BpmJsonModelDO queryVo){
        return JsonResult.success(bpmJsonModelService.page(queryVo));
    }

    @PostMapping("/page/exportList")
    @Operation(summary = "模型列表")
    public JsonResult<String> getModelExport(@RequestBody BpmJsonModelDO queryVo){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (CollectionUtil.isNotEmpty(queryVo.getIds())){
            queryWrapper.in("id",queryVo.getIds());
        }
        List<BpmJsonModelDO> exportList = bpmJsonModelService.pageExportList(queryVo, queryWrapper, new LinkedList<>());
        if (CollectionUtil.isNotEmpty(exportList)){
            exportList.forEach(item -> {
                item.setCreateUser(item.getCreateBy());
                item.setCreateDateStr(item.getCreateDate());
            });
        }
        Field[] fields = BpmJsonModelDO.class.getDeclaredFields();
        List<String> propertyNames = new ArrayList<>();
//        for (Field field : fields) {
//            propertyNames.add(field.getName());
//        }
        propertyNames.add("name");
        propertyNames.add("category");
        propertyNames.add("createUser");
        propertyNames.add("createDateStr");
        List<String> tableName = new ArrayList<>();
        tableName.add("模板名称");
        tableName.add("应用场景");
        tableName.add("操作人");
        tableName.add("操作时间");
        String url = exportService.createExcelFileDate(exportList,fields,propertyNames, tableName,"审批流程信息");
        return JsonResult.success(url);
    }



    @PutMapping("/approve")
    @Operation(summary = "执行任务")
    public JsonResult<Boolean> approveTask(@RequestBody BpmTaskApproveReqVO reqVO) {
        taskService.approveTask("", reqVO);
        return JsonResult.success(true);
    }



    /**
     * 根据流程定义获取文件信息
     * @param definitionId
     * @return
     */
    @Operation(summary = "根据流程定义获取文件信息")
    @GetMapping("/definitionId/{definitionId}")
    public JsonResult<List<TaskDto>> getTaskInfo(@PathVariable("definitionId") String definitionId){
        return taskService.getTaskInfo(definitionId);
    }

    @PutMapping("/updateJsonModel")
    @Operation(summary = "新增、修改流程文件")
    public JsonResult updateJsonModel(@RequestBody BpmJsonModelVO modelDO) throws InvocationTargetException, IllegalAccessException {
        return modelService.updateJsonModel(modelDO);
    }

    @GetMapping("/startProcessInstance/{key}")
    @Operation(summary = "根据流程key启动流程")
    public JsonResult startProcessInstance(@PathVariable("key") String key){
        Map<String,Object> map = new HashMap<>();
        return processInstanceService.createProcessInstance(key,map,"123");
    }

    @GetMapping("/cancelProcessInstanceId/{processsInstanceId}")
    public JsonResult cancelProcessInstanceId(@PathVariable("processsInstanceId") String processsInstanceId){
        processInstanceService.cancelProcessInstanceId(processsInstanceId);
        return JsonResult.success();
    }

    @Autowired
    private ExportService exportService;

    @PostMapping("/exportList")
    @Operation(summary = "待办任务列表")
    public JsonResult<String> exportList(@RequestBody BpmQueryVo taskReqVo){
        List<BpmTaskTodoItemRespVO> list = taskService.exportList(taskReqVo);
        Field[] fields = BpmTaskTodoItemRespVO.class.getDeclaredFields();
        List<String> propertyNames = new ArrayList<>();
//        for (Field field : fields) {
//            propertyNames.add(field.getName());
//        }
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(item -> {
                if (item.getStatus() != null){
                    if (0 == item.getStatus()){
                        item.setStatusStr("·审批中");
                    }
                    if (1 == item.getStatus()){
                        item.setStatusStr("·已通过");
                    }
                    if (2 == item.getStatus()){
                        item.setStatusStr("·已拒绝");
                    }
                }
            });
        }
        propertyNames.add("createBy");
        propertyNames.add("processName");
        propertyNames.add("reason");
        propertyNames.add("statusStr");
        propertyNames.add("startUserName");
        propertyNames.add("createTime");
        propertyNames.add("claimTime");
        List<String> tableName = new ArrayList<>();
        tableName.add("申请人");
        tableName.add("申请模块");
        tableName.add("申请信息");
        tableName.add("状态");
        tableName.add("审批人");
        tableName.add("申请时间");
        tableName.add("更新时间");
        String url = exportService.exportUtil(list,fields,propertyNames, tableName,"审批记录详细信息");
        return JsonResult.success(url);
    }


}
